﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AutoPublishWebSite
{
    class HttpServer
    {
        public void StartWebServer(int port, Func<string, string, string> func)
        {
            HttpListener httpListener = new HttpListener();

            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            httpListener.Prefixes.Add($"http://+:{port}/");
            httpListener.Start();
            Task.Factory.StartNew(() =>
            {
                while (true)
                {

                    HttpListenerContext httpListenerContext = httpListener.GetContext();
                    httpListenerContext.Response.StatusCode = 200;
                    httpListenerContext.Response.ContentType = "application/json";
                    using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream))
                    {
                        DoContextWork(httpListenerContext, writer, func);
                    }

                }
            });
        }
        void DoContextWork(HttpListenerContext context, StreamWriter writer, Func<string, string, string> func)
        {
            switch (context.Request.HttpMethod)
            {
                case "POST":
                    {
                        NameValueCollection head = context.Request.Headers;
                        //字节长度
                        string strLength = head.GetValues("Content-Length")[0];

                        //读取客户端发送过来的数据
                        using (Stream inputStream = context.Request.InputStream)
                        {
                            long logLength = Convert.ToInt64(strLength);

                            byte[] buffer = new byte[logLength];
                            //读取用户发送过来的正文
                            int jsonLength = inputStream.Read(buffer, 0, buffer.Length);

                            if (jsonLength <= 0) return;

                            //将其转为字符串
                            string postData = Encoding.UTF8.GetString(buffer, 0, jsonLength);
                            var res = func(context.Request.RawUrl, postData);
                            writer.Write(res);
                        }
                    }
                    break;
                case "GET":
                    {
                        var res = func(context.Request.Url.ToString(), null);
                        writer.Write(res);
                    }
                    break;
                default: throw new NotImplementedException();

            }
        }
    }
}
